<template>
  <div class="calendar_box">
    <el-row :gutter="20">
      <el-col :span="18">
        <FullCalendar class="fullCalendar" ref="fullCalendar" :options="calendarOptions"/>
      </el-col>
      <el-col :span="6" class="detail_box">
        <el-alert style="margin-top: 25px" title="茶道茶馆排班信息" type="success" :closable="false"></el-alert>
        <el-form :model="info" label-width="100px">
          <el-form-item label=""></el-form-item>
          <el-form-item label="排班标题：">{{ info.title }}</el-form-item>
          <el-form-item label="排班员工：">{{ info.staffName }}</el-form-item>
          <el-form-item label="排班时间：">{{ info.dutyTime }}</el-form-item>
          <el-form-item label="结束时间：">{{ info.end }}</el-form-item>
          <el-form-item label="联系电话：">{{ info.phone }}</el-form-item>
          <el-form-item label="工作邮箱：">{{ info.mail }}</el-form-item>
          <div class="addButton" style="text-align: right;margin-right: 20px;">
            <el-button type="danger" @click="delData" size="small" v-show="isShowBtn">删除</el-button>
          </div>
        </el-form>
      </el-col>
    </el-row>

    <!-- 添加或修改 -->
    <el-dialog title="添加排班" :visible.sync="dialogFormVisible">
      <el-form :model="form" label-width="80px" ref="form" :rules="rules">
        <el-form-item label="值班" prop="title">
          <el-input v-model="form.title" placeholder="请输入排班标题" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="排班员工" prop="staffId">
          <el-select v-model="form.staffId" value-key="id" @change="getInfo" placeholder="请选择员工">
            <el-option v-for="item in staffList" :key="item.id" :label="item.name" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排班时间" prop="time">
          <el-date-picker v-model="form.time" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" align="right" style="width: 100%"
                          start-placeholder="值班开始日期" end-placeholder="值班结束日期" :default-time="['08:00:00', '17:00:00']">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('form')" size="small">取 消</el-button>
        <el-button type="primary" @click="save('form')" size="small">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from "@fullcalendar/daygrid";
import interactionPlugin from "@fullcalendar/interaction";

export default {
  name: "StaffDuty",
  components: {
    FullCalendar // make the <FullCalendar> tag available
  },
  data() {
    return {
      isShowBtn: false,
      dialogFormVisible: false,
      form: {
        title: "",
        staffId: "",
        dutyTime: '',
        staffName: "",
        phone: '',
        mail: '',
        start: '',
        end: '',
        allDay: ''
      },
      formLabelWidth: 100,
      calendarOptions: {
        displayEventTime: true,   // 是否显示时间
        timeGridPlugin:true,      //  可显示每日时间段
        handleWindowResize: true, //随浏览器窗口变化
        height: 600,
        plugins: [dayGridPlugin, interactionPlugin],
        headerToolbar: {
          left: "prev,next today",
          center: "title",
          right: "dayGridMonth,dayGridWeek,dayGrid",
        },
        buttonText: {
          // 设置按钮
          today: "今天",
          month: "月",
          week: "周",
          dayGrid: "天",
          color: '#409EFF'
        },
        // allDaySlot: false,
        editable: true,
        selectable: true,
        navLinks: true,
        displayEventEnd: true,//所有视图显示结束时间
        initialView: "dayGridMonth", // 设置默认显示月，可选周、日
        // dateClick: this.handleDateClick,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        select: this.handleDateSelect,
        // 设置日程
        events: [],
        //events格式如下
        // {
        // 	id: 1,
        // 	title: '09:30~11:30 小破孩',
        // 	start: '2020-12-11',
        // 	end: '2020-12-13',
        // 	color: '#f08f00',
        // },
        eventColor: "#f08f00", // 修改日程背景色
        locale: "zh-cn", // 设置语言
        weekNumberCalculation: "ISO", // 周数
        customButtons: {}
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 6, message: '长度在 2 到 6个字符', trigger: 'blur'}
        ],
        staffId: [
          {required: true, message: '该选项必选', trigger: 'blur'},
        ],
        time: [
          {required: true, message: '请选择值班日期', trigger: 'blur'},
        ],
      },
      info: {},
      staffList: [],
      staffInfo: {},
      selectInfo: {},
      calendarApi: null
    }
  },
  mounted() {
    //  把日历对象赋值以便操作日历
    this.calendarApi = this.$refs.fullCalendar.getApi();
    this.getDuty();
    this.getUser()
  },
  methods: {
    //获取排班
    getDuty() {
      this.$axios.get('/api/com/findDuty').then(res => {
        if (res.data.status === 1) {
          console.log(res.data.data.list);
          this.calendarOptions.events = res.data.data.list
        }
      })
    },
    //获取所有员工
    getUser() {
      let param = {}
      param.isDel = 0
      this.$axios.get('/api/user/findUser', {params: this.param}).then(res => {
        this.staffList = res.data.data.list;
      }).catch(e => console.log(e));
    },
    //添加排班
    handleDateSelect(selectInfo) {
      this.dialogFormVisible = true;
      //保存当前日期的信息
      this.selectInfo = selectInfo
    },
    save(form) {
      this.$refs[form].validate((valid) => {
        if (valid){
          this.calendarApi.unselect() // clear date selection
          this.form.start = this.form.time[0]
          this.form.dutyTime = this.form.time[0]
          this.form.end = this.form.time[1]
          this.form.allDay = this.selectInfo.allDay
          this.form.staffId = this.staffInfo.id
          this.form.mail = this.staffInfo.mail
          this.form.phone = this.staffInfo.phone
          this.form.staffName = this.staffInfo.name
          // console.log(this.staffInfo)
          //往本地日历添加日程
          this.calendarApi.addEvent(this.form)
          // console.log(this.form)
          //向数据库添加日程
          this.$axios.post('/api/com/addDuty', this.form).then(res => {
            if (res.data.status === 1) {
              this.$notify({
                title: '提示',
                message: '添加成功!',
                type: 'success'
              })
              this.getDuty()
              this.resetForm(form)
            } else {
              this.$notify({
                title: '提示',
                message: res.data.message,
                type: 'error'
              })
            }
          })
          this.dialogFormVisible = false;
        }else {
          return false
        }
      })
    },
    getInfo(item) {
      this.staffInfo = item
    },
    //点击排班事件
    handleEventClick(calEvent) {
      this.isShowBtn = true;
      this.info = {}
      let data = calEvent.event;
      console.log(data)
      this.info.id = data.id
      this.info.dutyTime = data._def.extendedProps.dutyTime
      this.info.end = calEvent.event.endStr.split('T').join(' ').substring(0,19)
      this.info.title = data.title
      this.info.staffName = data._def.extendedProps.staffName
      this.info.phone = data._def.extendedProps.phone
      this.info.mail = data._def.extendedProps.mail
      // console.log(this.dateToString(calEvent.event.start))
    },
    //删除
    delData() {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.info.id
        return this.$axios.delete(`/api/com/delDuty?ids=${ids}`).then(res => {  //物理删除
          if (res.data.status === 1) {  //删除成功
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success'
            });
            this.getDuty();
            this.info={}
          } else {
            this.$notify({
              title: '提示',
              message: res.data.message,
              type: 'error'
            });
          }
        }).catch(e => e)
      });
    },
    handleEvents(events) {
      this.currentEvents = events
    },
    resetForm(from) {
      this.$nextTick(()=>{
        this.$refs[from].resetFields();
      })
      this.dialogFormVisible = false
    },
  }


}
</script>

<style scoped>
.addButton {
  margin-top: 15px;
  text-align: left;
  margin-bottom: 15px;
}

.calendar_box > > > .el-dialog {
  width: 450px;
}

.calendar_box > > > .el-date-editor.el-input {
  width: 330px;
}

.el-select {
  width: 100%;
}

.detail_box >>> .el-form {
  border: 1px solid #ddd;
}

.detail_box >>> .el-form-item__content {
  text-align: left;
  color: #333;
}
</style>
